package com.piece.admin.config;

import com.google.common.collect.Multimap;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.web.authority.AccessDecisionManagerCustomizer;
import com.piece.core.web.authority.AuthorityFactory;
import com.piece.core.web.properties.SecurityProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Component
public class OauthStompDecisionManager extends AccessDecisionManagerCustomizer {

    // 存放所有可匿名访问的url
    private List<RequestMatcher> matchers = new ArrayList<>();

    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private AuthorityFactory authorityFactory;
    @Resource
    private SecurityProperties securityProperties;

    @PostConstruct
    private void construct() {
        Multimap<HttpMethod, String> permits = authorityFactory.permitAllMethods(applicationContext, securityProperties);
        this.antMatchers(HttpMethod.GET.name(), permits.get(HttpMethod.GET).toArray(new String[0]));
        this.antMatchers(HttpMethod.POST.name(), permits.get(HttpMethod.POST).toArray(new String[0]));
        this.antMatchers(HttpMethod.PUT.name(), permits.get(HttpMethod.PUT).toArray(new String[0]));
        this.antMatchers(HttpMethod.DELETE.name(), permits.get(HttpMethod.DELETE).toArray(new String[0]));
    }

    @Override
    public void decide(HttpServletRequest request) {
        String url = request.getRequestURI();
        if (url.indexOf("/queue/oauth/callback") != -1) {
            return;
        } else if (!matcher(request)) {
            throw new AccessDeniedException(I18nUtil.message("auth.login.retry"));
        }
    }

    private void antMatchers(String method, String... antPatterns) {
        String[] var4 = antPatterns;
        int var5 = antPatterns.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            String pattern = var4[var6];
            matchers.add(new AntPathRequestMatcher(pattern, method));
        }
    }

    private boolean matcher(HttpServletRequest request) {
        for (RequestMatcher matcher : matchers) {
            if (matcher.matches(request)) {
                return true;
            }
        }

        return false;
    }
}
